package top.java.multithreading;


import org.junit.Test;

/**
 *       线程安全问题
 *
 *          方式二：    同步方法
 *
 *          如果操作共享数据的代码完整的声明在一个方法中，我们不妨将此方法声明为同步的
 *
 *          实现Runnable接口的方式   将操作共享数据的代码放入一个方法中，将该方法用synchronized修饰
 *          继承Thread类的方式    将操作共享数据的代码放入一个方法中，将该方法用synchronized和static修饰
 *
 *          同步方法仍然涉及到同步监视器，只是不需要显式的声明
 *          非静态的同步方法为this       静态的同步方法为  当前类.class
 */


public class ThreadTest5 {

    public static void main(String[] args) {

        Window6 window6 = new Window6();
        Thread thread = new Thread(window6);
        Thread thread2 = new Thread(window6);
        Thread thread3 = new Thread(window6);

        thread.setName("窗口1");
        thread2.setName("窗口2");
        thread3.setName("窗口3");

        thread.start();
        thread2.start();
        thread3.start();
        while (true) {
            if (!(thread.isAlive() && thread2.isAlive() && thread3.isAlive())) {
                break;
            }
        }
    }

    @Test
    public void test5() {
        Window7 window5 = new Window7();
        Window7 window6 = new Window7();
        Window7 window7 = new Window7();

        window5.setName("窗口一");
        window6.setName("窗口二");
        window7.setName("窗口三");

        window5.start();
        window6.start();
        window7.start();
        while (true) {
            if (!(window5.isAlive() && window6.isAlive() && window7.isAlive())) {
                break;
            }
        }
    }
}

class Window6 implements Runnable {

    private int ticket = 100;

    @Override
    public void run() {
       while (true) {
           show();
       }
    }

    private synchronized void show() {
        if (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + "票号为：" + ticket);
            ticket--;
        }
    }
}


/**
 *              继承方式
 */

class Window7 extends Thread{

    private static int title = 100;

    @Override
    public void run() {
       while (true) {
           show();
       }
    }

    private static synchronized void show() {
        if (title > 0) {
            System.out.println(Thread.currentThread().getName() + "票号为：" + title);
            title--;
        }
    }
}
